package com.ihomey.linkuphome.ui;

import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.github.ikidou.fragmentBackHandler.BackHandlerHelper;
import com.github.ikidou.fragmentBackHandler.FragmentBackHandler;
import com.ihomey.cc.library.util.DensityUtil;
import com.ihomey.linkuphome.DeviceController;
import com.ihomey.linkuphome.R;
import com.ihomey.linkuphome.SpacesItemDecoration;
import com.ihomey.linkuphome.WrapContentLinearLayoutManager;
import com.ihomey.linkuphome.adapter.ControlDeviceListAdapter;
import com.ihomey.linkuphome.adapter.LightFragmentAdapter;
import com.ihomey.linkuphome.base.BaseFragment;
import com.ihomey.linkuphome.entities.Device;
import com.ihomey.linkuphome.listeners.OnBottomTabClickListener;
import com.ihomey.linkuphome.listeners.OnItemClickListener;
import com.ihomey.linkuphome.util.BindView;
import com.ihomey.linkuphome.widget.BottomTabLayout;
import com.ihomey.linkuphome.widget.CustomViewpager;
import com.ihomey.linkuphome.widget.TabIconView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/6/9.
 */

public class LightFragment extends BaseFragment implements OnItemClickListener, FragmentBackHandler {

    private static final int CHECKING_SCAN_INFO_TIME_MS = (5 * 1000);

    private LightFragmentAdapter mAdapter;
    @BindView(id = R.id.vp_content)
    private CustomViewpager vp_content;
    @BindView(id = R.id.bottomTabLayout)
    private BottomTabLayout bottomTabLayout;
    @BindView(id = R.id.rcv_control_unit)
    public RecyclerView rcv_control_unit;
    @BindView(id = R.id.blackView)
    public View blackView;
    private View tabView;
    private TabIconView tabIconView;
    private TextView tabTextView;

    private DeviceController mController;
    private MainActivity mainActivity;

    public BottomSheetBehavior behavior;
    private List<Device> controlDeviceList = new ArrayList<>();
    private ControlDeviceListAdapter controlDeviceListAdapter;


    public static LightFragment newInstance(int lightType) {
        LightFragment fragment = new LightFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("lightType", lightType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.fragment_light, null);
        view.setBackgroundResource(mController.getDeviceType() == 1 ? R.drawable.light_lawn_bg : R.drawable.light_rgb_bg);
        return view;
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mainActivity = (MainActivity) activity;
            mController = (DeviceController) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DeviceController callback interface.");
        }
    }

    @Override
    public void initData() {
        super.initData();
        mAdapter = new LightFragmentAdapter(getActivity(), getChildFragmentManager(), mController.getDeviceType());
        controlDeviceListAdapter = new ControlDeviceListAdapter(controlDeviceList);
        controlDeviceListAdapter.setOnItemClickListener(this);
    }

    private Runnable checkScanInfoRunnable = new Runnable() {
        @Override
        public void run() {
            ((MainActivity) getActivity()).getMeshHandler().postDelayed(checkScanInfoRunnable, CHECKING_SCAN_INFO_TIME_MS);
        }
    };

    @Override
    public void initWidget(View parentView) {
        super.initWidget(parentView);
        mainActivity.showBackBtn(true);
        vp_content.setScrollable(false);
        vp_content.setOffscreenPageLimit(3);
        vp_content.setAdapter(mAdapter);
        vp_content.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (position != 1) {
                    mController.discoverDevices(false, null);
                    mController.removeRunnable(checkScanInfoRunnable);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        bottomTabLayout.setViewPager(vp_content);
        bottomTabLayout.setOnBottomTabClickListener(new OnBottomTabClickListener() {
            @Override

            public void onTabSelected(int position) {
                unSelectTabView();
            }
        });

        behavior = BottomSheetBehavior.from(rcv_control_unit);
        behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED || newState == BottomSheetBehavior.STATE_HIDDEN) {
                    blackView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                blackView.setVisibility(View.VISIBLE);
                ViewCompat.setAlpha(blackView, slideOffset);
            }
        });
        initSelectTabView(parentView);
        initBlackView();
        initRecycleView();
    }


    private void initRecycleView() {
        rcv_control_unit.setPadding(DensityUtil.dip2px(getActivity(), 8), DensityUtil.dip2px(getActivity(), 8), DensityUtil.dip2px(getActivity(), 8), DensityUtil.dip2px(getActivity(), 8));
        rcv_control_unit.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        rcv_control_unit.addItemDecoration(new SpacesItemDecoration(DensityUtil.dip2px(getActivity(), 2)));
        rcv_control_unit.setAdapter(controlDeviceListAdapter);
        rcv_control_unit.setItemAnimator(new DefaultItemAnimator());
    }

    private void initBlackView() {
        blackView.setBackgroundColor(Color.parseColor("#a0000000"));
        blackView.setVisibility(View.GONE);
        blackView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unSelectTabView();
            }
        });
    }

    private void initSelectTabView(View parentView) {
        tabView = LayoutInflater.from(mainActivity).inflate(R.layout.layout_bottom_tab, null);
        tabIconView = (TabIconView) tabView.findViewById(R.id.main_bottom_tab_icon);
        tabIconView.init(R.drawable.icon_tab_control_normal, R.drawable.icon_tab_control_select);
        tabTextView = (TextView) tabView.findViewById(R.id.main_bottom_tab_text);
        tabTextView.setText(R.string.tab_control_select);
        if (tabView == null) {
            throw new IllegalStateException("tabView is null.");
        }
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.weight = 1;
        LinearLayout aa = (LinearLayout) parentView.findViewById(R.id.aa);
        aa.addView(tabView, lp);
        tabView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<Device> devices = new ArrayList<>();
                devices.addAll(mController.getGroups());
                devices.addAll(mController.getDevices());
                controlDeviceListAdapter.replaceAll(devices);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (tabView.getTag() != null && (boolean) tabView.getTag()) {
                            unSelectTabView();
                        } else {
                            selectTabView();
                        }
                    }
                }, 100);
            }
        });
    }

    private void selectTabView() {
        tabIconView.transformPage(0);
        tabTextView.setTextColor(getResources().getColor(R.color.main_bottom_tab_textcolor_selected));
        tabView.setTag(true);
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        bottomTabLayout.unSelectItem(vp_content.getCurrentItem());
    }

    private void unSelectTabView() {
        tabIconView.transformPage(1);
        tabTextView.setTextColor(getResources().getColor(R.color.main_bottom_tab_textcolor_normal));
        tabView.setTag(null);
        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        bottomTabLayout.selectItem(vp_content.getCurrentItem());
    }

    @Override
    public void onItemClick(int position) {
        if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
        if (position != controlDeviceListAdapter.getItemCount() - 1) {
            Device device = controlDeviceListAdapter.getItem(position);
            updateControls(device.getDeviceId());
        } else {
            new MaterialDialog.Builder(getActivity()).content(R.string.devices_clear).canceledOnTouchOutside(false).negativeText(R.string.cancel).negativeColorRes(R.color.colorPrimary).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    unSelectTabView();
                }
            }).positiveText(R.string.confirm).positiveColorRes(R.color.colorPrimary).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(MaterialDialog dialog, DialogAction which) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            final boolean isShare = mainActivity.getSharedPreferences("ihomey", Activity.MODE_PRIVATE).getBoolean("isShare" + mController.getDeviceType(), false);
                            if (isShare) {
                                mController.removeAllDevices();
                                SharedPreferences activityPrefs = mainActivity.getSharedPreferences("ihomey", Activity.MODE_PRIVATE);
                                SharedPreferences.Editor editor = activityPrefs.edit();
                                editor.putBoolean("isShare" + mController.getDeviceType(), false);
                                editor.commit();
                            } else {
                                mController.removeAllGroupDevices();
                            }
                            mainActivity.runOnUiThread(new Runnable() {
                                public void run() {
                                    if (vp_content.getCurrentItem() == 2) {
                                        GroupParentFragment groupParentFragment = (GroupParentFragment) getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_content + ":" + 2);
                                        if (groupParentFragment != null && groupParentFragment.isVisible()) {
                                            groupParentFragment.refreshGroupFragment();
                                        }
                                    } else if (isShare && vp_content.getCurrentItem() == 1) {
                                        DeviceFragment deviceFragment = (DeviceFragment) getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_content + ":" + 1);
                                        if (deviceFragment != null && deviceFragment.isVisible()) {
                                            deviceFragment.onVisible();
                                        }
                                    }
                                    unSelectTabView();
                                }
                            });
                        }
                    }).start();
                }
            }).build().show();
        }
    }


    @Override
    public boolean onBackPressed() {
        if (behavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            unSelectTabView();
            return true;
        } else {
            return BackHandlerHelper.handleBackPress(this);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        mController.discoverDevices(false, null);
        mController.removeRunnable(checkScanInfoRunnable);
    }

    private static final String DEVICE_LAST_ID = "lastDeviceID";

    public void updateControls(int selectedDeviceId) {
//        SharedPreferences activityPrefs = getActivity().getSharedPreferences("ihomey", Activity.MODE_PRIVATE);
//        SharedPreferences.Editor editor = activityPrefs.edit();
//        editor.remove(DEVICE_LAST_ID + mController.getDeviceType());
//        editor.commit();
        ControlParentFragment controlParentFragment = (ControlParentFragment) getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.vp_content + ":" + 0);
        controlParentFragment.storeLightState();
        mController.setSelectedDeviceId(selectedDeviceId);

        SharedPreferences activityPrefs = getActivity().getSharedPreferences("ihomey", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = activityPrefs.edit();
        editor.putInt(DEVICE_LAST_ID + mController.getDeviceType(), mController.getSelectedDeviceId());
        editor.commit();

        tabIconView.transformPage(1);
        tabTextView.setTextColor(getResources().getColor(R.color.main_bottom_tab_textcolor_normal));
        tabView.setTag(null);
        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        bottomTabLayout.selectItem(0);
        vp_content.setCurrentItem(0);

        controlParentFragment.updateControlName();
    }
}
